package org.endy.leisure.diaTracker.service

import org.endy.leisure.diaTracker.entity.User
import org.endy.leisure.diaTracker.repository.UserRepository
import org.springframework.stereotype.Service
import java.util.*

@Service
class UserService(private val userRepository: UserRepository) {

    /**
     * 用户登录接口
     */
    fun login(openid: String?, phone: String): User? {
//        return userRepository.findUserByOpenIdOrPhone(openid, phone = phone)
        return userRepository.findUserByPhone(phone)
    }

    /**
     * 用户信息更新接口
     */
    fun updateUser(user: User) {
        userRepository.findById(user.id!!).ifPresent { oldUser ->
            with(oldUser) {
                nickname = user.nickname
                password = user.password
                avatar = user.avatar
                isVerified = user.isVerified
                lastLogin = Date()
            }
            userRepository.save(oldUser)
        }

    }

    /**
     * 根据手机号码更新用户角色
     */
    fun updateUserRoleByPhone(phone: String, roleType: String): User? {
        return userRepository.findUserByPhone(phone = phone)?.let { user ->
            user.roleType = roleType
            userRepository.save(user)
        }
    }

    /**
     * 根据用户的openId创建用户信息，如果用户存在直接返回，不存在则创建
     */
    fun createUser(user: User): User {
        userRepository.findUserByPhone(user.phone!!)?.let {
            throw RuntimeException("用户已经存在！！")
        }
        return userRepository.save(user)

    }

}